<template>
  <div class="Transfers" v-loading="loading" element-loading-text="拼命加载中">
    <div class="Transfers-type">
      <div>
        <div>重要提示：</div>
        <div style="margin: 6px 0">
          批发打款请汇入正确银行账户，具体信息见下方备注！
        </div>
        <div v-if="is_subject == 'kz'">
          <span>户名：年年有余 (浙江)文化科技有限公司</span>
          <span style="margin: 0 20px">开户行：杭州联合银行九堡支行</span>
          <span>账号：201000242198455</span>
        </div>
        <div v-if="is_subject == 'mz'">
          <span>户名：杭州妙哉文化有限公司</span>
          <span>开户行：上海浦东发展银行杭州分行营业部</span>
          <span>账号：95200078801000002375</span>
        </div>
      </div>
    </div>
    <div class="Transfers-plan">
      <div class="line">批发商品信息</div>
      <div class="Transfers-list">
        <div class="Transfers-list-module">
          <div class="Transfers-list-module-search">
            <el-input v-model="number" style="width: 400px" placeholder="请输入款号/款名/SKU" size="mini"
              @keyup.enter.native="onSearch" clearable>
              <el-button slot="append" icon="el-icon-search" @click="onSearch"></el-button>
            </el-input>
            <el-upload action="https://ssy.13yu.com/index.php/Admin/Excel/allocationExcel" :headers="headers"
              :on-success="handleSuccess" :data="{ groups }">
              <el-button size="mini" style="margin: 0 20px" type="primary">批量导入</el-button>
            </el-upload>
            <div class="pointer" style="width: 120px; display: flex; align-items: center" @click="onDownloadexcel">
              <el-image style="width: 20px; height: 20px; margin-right: 5px" :src="excel" fit="contain"></el-image>
              <span style="border-bottom: 1px solid #333">下载示例</span>
            </div>
          </div>
          <div class="Transfers-list-module-content myscroll">
            <el-table size="mini" :data="tableData" height="400" style="width: 100%"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="img" label="图片" width="80">
                <template slot-scope="{ row }">
                  <el-image style="width: 50px; height: 50px" :src="row.img" fit="contain"
                    :preview-src-list="[row.img]"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="product_name" label="款名">
              </el-table-column>
              <el-table-column prop="sku_code" label="SKU"> </el-table-column>
              <!-- <el-table-column prop="selling_price" label="原价金额">
              </el-table-column> -->
            </el-table>
          </div>
        </div>
        <div style="margin: 0 20px">
          <el-button type="primary" :disabled="!multipleSelection.length" @click="onAdd">加入批发计划<i
              class="el-icon-arrow-right el-icon--right"></i></el-button>
        </div>
        <div class="Transfers-list-module" style="width: 900px">
          <div class="Transfers-list-module-search">申请计划列表</div>
          <div class="Transfers-list-module-content myscroll">
            <el-table size="mini" :data="TableDataSelect" height="400" style="width: 100%">
              <el-table-column prop="img" label="图片" width="80">
                <template slot-scope="{ row }">
                  <el-image style="width: 50px; height: 50px" :src="row.img" fit="contain"
                    :preview-src-list="[row.img]"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="product_name" label="款名">
              </el-table-column>
              <el-table-column prop="sku_code" label="SKU" width="160">
              </el-table-column>
              <el-table-column prop="selling_price" label="单价" width="160">
                <template slot-scope="{ row, $index }">
                  <el-input style="width: 140px" type="number" v-model="row.selling_price" placeholder="请输入单价" size="mini"
                    @input="onInputSelling_price($event, $index)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="折扣 (例:6折请输入0.6)" width="150">
                <template slot-scope="{ row, $index }">
                  <el-input type="number" v-model="row.discount" placeholder="请输入折扣" size="mini"
                    @input="onInputdiscount($event, $index)"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="num" label="批发数">
                <template slot-scope="{ row, $index }">
                  <el-input type="number" v-model="row.num" placeholder="请输入批发数" size="mini"
                    @input="onInput($event, $index)"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="zh_price" label="折后金额">
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="{ $index }">
                  <el-button type="text" size="default" style="color: red" @click="onDelete($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="summary">
        <div>
          数量汇总：<span style="color: #2c70d6">{{ Summary.num }}</span>
        </div>
        <div>
          原价金额汇总：<span>{{ Summary.selling_price }}</span>
        </div>
        <div>
          折扣金额(元)汇总：<span style="color: red">{{
            Summary.zh_price
          }}</span>
        </div>
      </div>
      <div style="margin-top: 20px">
        <div class="line" style="font-weight: 600; font-size: 14px">
          邮寄信息
        </div>
        <div class="info">
          <div>
            <div class="star">联系人</div>
            <div>
              <el-input v-model="wp_user" placeholder="请输入联系人" size="mini" clearable></el-input>
            </div>
          </div>
          <div>
            <div class="star">联系电话</div>
            <div>
              <el-input v-model="wp_phone" placeholder="请输入联系电话" size="mini" type="number" clearable></el-input>
            </div>
          </div>
          <div>
            <div class="star">邮寄地址</div>
            <div>
              <el-cascader ref="cascaderlabel" style="width: 400px" size="mini" :options="address"
                v-model="selectedOptions" slot="prepend" placeholder="请选择省市区" @change="handleChange">
              </el-cascader>
              <el-input v-model="wp_address" placeholder="请输入详细地址" size="mini" clearable></el-input>
            </div>
          </div>
        </div>
        <div class="info">
          <div>
            <div class="star">付款信息（ 只允许上传一张图片 ）</div>
            <div>
              <el-upload action="https://ssy.13yu.com/index.php/Admin/Api/upload" :on-success="handleSuccessXJ"
                :before-remove="handleRemovesXJ" list-type="picture-card" limit="1" :disabled="images.length >= 1"
                :file-list="images">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <div class="fileimg">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" />
                  </div>
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemovesXJ(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
      <div style="margin-top: 20px">
        <el-button type="primary" size="small" :disabled="!TableDataSelect.length ||
          !wp_user ||
          !wp_phone ||
          !wp_address ||
          !wp_province ||
          !wp_city ||
          !wp_area ||
          !images.length
          " @click="onSubmit">确 定</el-button>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisibleImage" :modal="false">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  postAdminOmsGetAllocationType,
  postAdminOmssetAllocation_wholesale,
  postAdminOmsgetlogisticsCompanyCode,
  postAdminOmsgetAllocationExcel
} from "@/api";
import { getStore } from "@/utils/localStorage.js";
import { regionData } from "element-china-area-data";
import { floatMultiply, floatAdd } from "@/utils/algorithm.js";
import excel from "@/assets/images/excel.png";
export default {
  data() {
    return {
      headers: {},
      groups: 4,
      excel,
      number: "",
      loading: false,
      dialogVisibleImage: false,
      address: regionData,
      Couriertype: "",
      selectedOptions: [],
      Courier: [],
      wp_phone: "",
      wp_address: "",
      wp_user: "",
      wp_province: "",
      wp_city: "",
      wp_area: "",
      images: [],
      dialogImageUrl: "",
      tableData: [],
      multipleSelection: [],
      TableDataSelect: [],
      Summary: {
        num: 0,
        selling_price: 0,
        zh_price: 0,
      },
      is_subject: "kz"
    };
  },
  mounted() {
    this.headers = {
      token: getStore("userinfo").token
    };
    this.is_subject = getStore("userinfo").is_subject;
    this.postAdminOmsgetlogisticsCompanyCode();
  },
  methods: {
    onDownloadexcel() {
      window.open(
        "https://ssy.13yu.com/Public/excel/moban/%E5%80%9F%E8%B5%A0%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
      );
    },
    async handleSuccess(response, file, fileList) {
      this.loading = true;
      let obj = {};
      if (response.code == 0) {
        obj.identification = response.data.identification;
      } else {
        this.loading = false;
        this.$message.warning(response.msg);
        return;
      }
      try {
        let res = await postAdminOmsgetAllocationExcel(obj);
        let multipleSelection = res.data;
        let { TableDataSelect } = this;
        multipleSelection = multipleSelection.map((e) => {
          if (!e.num) {
            e.num = 1;
          }
          e.sku_code = e.sku;
          return e;
        });
        let arr = [];
        for (let index = 0; index < multipleSelection.length; index++) {
          let is = TableDataSelect.some((e) => {
            return e.sku_code == multipleSelection[index].sku_code;
          });
          if (!is) {
            arr.push(multipleSelection[index]);
          }
        }
        TableDataSelect.push(...arr);
        this.TableDataSelect = TableDataSelect;
        this.loading = false;
      } catch (error) {
        this.loading = true;
      }
    },
    TableDataSelectSummary() {
      let { TableDataSelect } = this;
      let Summary = {
        num: 0,
        selling_price: 0,
        zh_price: 0,
      };
      TableDataSelect.forEach((e) => {
        if (e.num) {
          Summary.num = floatAdd(Summary.num, e.num);
        }
        if (e.selling_price) {
          Summary.selling_price = floatAdd(
            Summary.selling_price,
            floatMultiply(e.selling_price, e.num)
          );
        }
        if (e.zh_price) {
          Summary.zh_price = floatAdd(Summary.zh_price, e.zh_price);
        }
      });
      this.Summary = Summary;
    },
    changeselectCouriertype(e) {
      console.log("e", e);
      if (e != "快递") {
        this.remark = e;
      } else {
        this.remark = "";
      }
    },
    async postAdminOmsgetlogisticsCompanyCode() {
      let res = await postAdminOmsgetlogisticsCompanyCode();
      this.Courier = res.data;
    },
    handleChangeCourier(val) {
      this.transport_type = this.Courier.find(
        (item) => item.logistics_company_code == val
      ).logistics_company_name;
    },
    // 省市区
    handleChange(e) {
      if (e.length) {
        let label = this.$refs.cascaderlabel.getCheckedNodes();
        let arr = label[0].pathLabels;
        this.wp_province = arr[0];
        this.wp_city = arr[1];
        this.wp_area = arr[2];
      } else {
        this.wp_province = "";
        this.wp_city = "";
        this.wp_area = "";
      }
    },
    onInput(e, index) {
      let { TableDataSelect } = this;
      let tmpObj = TableDataSelect[index];
      if (Number(e)) {
        tmpObj.num = e;
        if (tmpObj.selling_price && tmpObj.discount) {
          tmpObj.zh_price = floatMultiply(
            floatMultiply(Number(tmpObj.selling_price), tmpObj.discount),
            e
          );
        } else {
          tmpObj.zh_price = 0;
        }
      } else {
        tmpObj.num = 1;
        if (tmpObj.selling_price && tmpObj.discount) {
          tmpObj.zh_price = floatMultiply(
            Number(tmpObj.selling_price),
            tmpObj.discount
          );
        } else {
          tmpObj.zh_price = 0;
        }
      }
      this.$set(this.TableDataSelect, index, tmpObj);
      this.TableDataSelectSummary();
    },
    onInputSelling_price(e, index) {
      let { TableDataSelect } = this;
      let tmpObj = TableDataSelect[index];
      if (Number(e)) {
        tmpObj.selling_price = e;
        if (tmpObj.num && tmpObj.discount) {
          tmpObj.zh_price = floatMultiply(
            floatMultiply(Number(tmpObj.selling_price), tmpObj.discount),
            tmpObj.num
          );
        } else {
          tmpObj.zh_price = 0;
        }
      } else {
        tmpObj.selling_price = "";
        tmpObj.zh_price = 0;
      }
      this.$set(this.TableDataSelect, index, tmpObj);
      this.TableDataSelectSummary();
    },
    onInputdiscount(e, index) {
      let { TableDataSelect } = this;
      let tmpObj = TableDataSelect[index];
      if (Number(e)) {
        tmpObj.discount = e;
        if (tmpObj.num && tmpObj.selling_price) {
          tmpObj.zh_price = floatMultiply(
            floatMultiply(Number(tmpObj.selling_price), tmpObj.discount),
            tmpObj.num
          );
        } else {
          tmpObj.zh_price = 0;
        }
      } else {
        tmpObj.discount = "";
        tmpObj.zh_price = 0;
      }
      this.$set(this.TableDataSelect, index, tmpObj);
      this.TableDataSelectSummary();
    },
    async onSearch() {
      this.loading = true;
      let { number } = this;
      let obj = {
        number,
      };
      if (!number) {
        return false;
      }
      try {
        let res = await postAdminOmsGetAllocationType(obj);
        this.tableData = res.data;
        this.multipleSelection = [];
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    onAdd() {
      let { multipleSelection, TableDataSelect } = this;
      multipleSelection = multipleSelection.map((e) => {
        e.num = 1;
        e.selling_price = "";
        e.discount = 0.68
        return e;
      });
      let arr = [];
      for (let index = 0; index < multipleSelection.length; index++) {
        let is = TableDataSelect.some((e) => {
          return e.sku_code == multipleSelection[index].sku_code;
        });
        if (!is) {
          let obj = {
            ...multipleSelection[index],
            zh_price: floatMultiply(
              Number(multipleSelection[index].selling_price),
              0.68
            ),
          };
          console.log("obj", obj);
          arr.push(obj);
        }
      }
      TableDataSelect.push(...arr);
      this.TableDataSelect = TableDataSelect;
    },
    onDelete(e) {
      let { TableDataSelect } = this;
      this.$confirm("确定删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          TableDataSelect.splice(e, 1);
          this.TableDataSelect = TableDataSelect;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSuccessXJ(response) {
      let { images } = this;
      let obj = {
        name: "图片",
        url: response.img,
      };
      images.push(obj);
      this.images = images;
    },
    handleRemovesXJ(file) {
      let { images } = this;
      let index = images.findIndex((e) => e.url == file.url);
      images.splice(index, 1);
      this.images = images;
      return true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImage = true;
    },
    async onSubmit() {
      this.loading = true;
      let {
        TableDataSelect,
        wp_user,
        wp_phone,
        wp_address,
        wp_province,
        wp_city,
        wp_area,
        images,
      } = this;

      let is = TableDataSelect.some((e) => {
        return !e.selling_price;
      });
      let isdiscount = TableDataSelect.some((e) => {
        return !e.discount;
      });
      if (is) {
        this.loading = false;
        return this.$message.warning("请输入正确的单价");
      }
      if (isdiscount) {
        this.loading = false;
        return this.$message.warning("请输入正确的折扣");
      }

      let arr = [];
      for (let index = 0; index < TableDataSelect.length; index++) {
        let obj = {
          sku_code: TableDataSelect[index].sku_code,
          num: TableDataSelect[index].num,
          price: TableDataSelect[index].selling_price,
          discount: TableDataSelect[index].discount
        };
        arr.push(obj);
      }
      let obj = {
        wp_user,
        wp_phone,
        wp_province,
        wp_city,
        wp_area,
        wp_address,
        images,
        arrlist: arr,
        types: "",
      };
      try {
        let res = await postAdminOmssetAllocation_wholesale(obj);
        this.$message.success("提交成功");
        this.loading = false;
        this.number = "";
        this.wp_phone = "";
        this.wp_address = "";
        this.wp_user = "";
        this.wp_province = "";
        this.wp_city = "";
        this.wp_area = "";
        this.Couriertype = "";
        this.tableData = [];
        this.multipleSelection = [];
        this.TableDataSelect = [];
        this.selectedOptions = [];
        this.Summary = {
          num: 0,
          selling_price: 0,
          zh_price: 0,
        };
        this.images = [];
      } catch (error) {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.summary {
  margin-top: 10px;
  border: 1px dashed #999;
  display: flex;
  padding: 10px;
  justify-content: center;

  >div {
    padding: 0 20px;

    >span {
      font-weight: 600;
    }
  }
}

.info {
  display: flex;
  margin-top: 15px;

  >div {
    margin-right: 20px;

    > :nth-child(1) {
      font-size: 12px;
      margin-bottom: 10px;
    }

    >div:nth-child(2) {
      display: flex;
      align-items: center;
    }
  }
}

.myscroll {
  overflow-y: scroll;
  overflow-x: hidden;
}

.myscroll::-webkit-scrollbar {
  display: none;
}

// 隐藏滚动条
.Transfers {
  background: #fff;
  font-size: 14px;
  padding: 20px 0;

  .Transfers-type {
    // display: flex;
    // align-items: center;

    >div {
      padding: 10px 20px;
      margin: 0 20px 10px;
      background: #efefef;
      border-radius: 8px;

      >div:nth-child(1) {
        font-weight: 600;
      }

      >div:nth-child(2) {
        color: red;
      }
    }

    >div:nth-child(2) {
      padding: 10px 20px;
      margin: 0 20px 10px;
      background: #efefef;
      border-radius: 8px;

      >div:nth-child(1) {
        font-weight: 400;
      }

      >div:nth-child(2) {
        color: #333;
        margin-left: 10px;

        >div {
          >span {
            margin-left: 10px;
            color: #2c70d6;
          }
        }
      }
    }
  }

  .Transfers-plan {
    padding: 10px 20px;

    /deep/ .el-upload-list {
      display: none;
    }

    >div:nth-child(1) {
      font-weight: 600;
      margin-bottom: 20px;
    }

    .Transfers-list {
      display: flex;
      align-items: center;

      .Transfers-list-module {
        border: 1px solid #efefef;
        width: 600px;
        border-radius: 4px;

        .Transfers-list-module-search {
          padding: 0 20px;
          height: 48px;
          display: flex;
          align-items: center;
          background-color: #f5f7fa;
          font-weight: 600;
          font-size: 12px;
        }

        .Transfers-list-module-content {
          height: 400px;

          /deep/ .el-table__row {
            height: 53px;
          }
        }
      }
    }
  }
}
</style>